package com.help10000.rms.mvp.presenter

import android.util.Log
import com.amir.common.api.CustomObserver
import com.amir.common.beans.OrderDetailEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.Utils
import com.help10000.rms.mvp.view.OrderDetailsView
import com.help10000.rms.ui.activitys.OrderDetailActivity
import com.help10000.rms.utils.LocationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class OrderDetailsPresenter(view: OrderDetailsView) : BasePresenter<OrderDetailsView>(view) {
    // 自定义协程作用域，绑定生命周期（Job用于取消）
    private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())


    /**
     * 获取订单详情
     */
    fun getOrderDetail(repairId: String,activity:OrderDetailActivity) {
        CoroutineScope(Dispatchers.IO).launch {
            val (lat, lng) = LocationManager.getLocation(activity)
            Log.d("获取订单详情定位", "获取到经纬度：lat=$lat, lng=$lng")
            val accessToken = SPUtils.getString(Constant.AccessToken)
            val latitude = lat
            val longitude = lng
            val orderDetails = Model.getServer()
                .orderDetails(accessToken, repairId, lat = latitude, lng = longitude)
            withContext(Dispatchers.Main) {
                Model.getObservable(
                    orderDetails,
                    object : CustomObserver<OrderDetailEntity>(mvpView) {
                        override fun success(t: OrderDetailEntity) {
                            mvpView?.descSuccess(t.data)
                        }
                    })
            }
        }

    }
    // 在Presenter销毁时调用，取消所有协程
    fun onDestroy() {
        coroutineScope.cancel()
    }


}